/*
 * ----------------Modal box-------------
 */
(function($) {
    $.fn.mdlg = function(options) {
        var defaults = {
            title: '标题',
            width:'',
            content: '<p>内容</p>',
            showCloseButton: true,
            buttons: [],
            buttonStyles: [],
            bootstrapModalOption: {},
            onShow: function() {},
            onShown: function() {},
            onHide: function() {},
            onHidden: function() {},
            onButtonClick: function(sender, modal, index) {},
        };
        options = $.extend(defaults, options);
        var modalID = '';

        // 生成一个惟一的ID
        function random(a, b) {
            return Math.random() > 0.5 ? -1 : 1;
        }

        function getModalID() {
            return "mdlg-" + ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'Q', 'q', 'W', 'w', 'E', 'e', 'R', 'r', 'T', 't', 'Y', 'y', 'U', 'u', 'I', 'i', 'O', 'o', 'P', 'p', 'A', 'a', 'S', 's', 'D', 'd', 'F', 'f', 'G', 'g', 'H', 'h', 'J', 'j', 'K', 'k', 'L', 'l', 'Z', 'z', 'X', 'x', 'C', 'c', 'V', 'v', 'B', 'b', 'N', 'n', 'M', 'm'].sort(random).join('').substring(5, 20);
        }

        $.fn.extend({
            closeDialog: function(modal) {
                modal.modal('hide');
            },
            setContent: function(cont){
            	$('#'+modalID).find('.modal-body').html(cont);
            }
        });

        return this.each(function() {
            var obj = $(this);
            modalID = getModalID();
            var tmpHtml = '<div class="modal fade" id="{ID}" role="dialog" aria-hidden="true"><div class="modal-dialog" style="width:{width}"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button><h4 class="modal-title">{title}</h4></div><div class="modal-body">{body}</div><div class="modal-footer">{button}</div></div></div></div>';
            var buttonHtml = '<button class="btn btn-default" data-dismiss="modal" aria-hidden="true">关闭</button>';
            if (!options.showCloseButton && options.buttons.length > 0) {
                buttonHtml = '';
            }
            // 生成按钮
            var btnClass = 'cls-' + modalID;
            for (var i = 0; i < options.buttons.length; i++) {
                buttonHtml += '<button buttonIndex="' + i + '" class="' + btnClass + ' btn ' + options.buttonStyles[i] + '">' + options.buttons[i] + '</button>';
            }
            // 替换模板标记
            tmpHtml = tmpHtml.replace(/{ID}/g, modalID).replace(/{width}/,options.width).replace(/{title}/g, options.title).replace(/{body}/g, options.content).replace(/{button}/g, buttonHtml);
            obj.append(tmpHtml);

            var modalObj = $('#' + modalID);
            // 绑定按钮事件,不包括关闭按钮
            $('.' + btnClass).click(function() {
                var index = $(this).attr('buttonIndex');
                options.onButtonClick($(this), modalObj, index);
            });
            // 绑定本身的事件
            modalObj.on('show.bs.modal', function() {
                options.onShow();

                var height = $('iframe:visible',window.top.document).height();
                // var headerHeight =
				// modalObj.find('.modal-header').outerHeight();
                // var footerHeight =
				// modalObj.find('.modal-footer').outerHeight();

				modalObj.find('.modal-body').css("max-height",(height - 170)+'px');
            });
            modalObj.on('shown.bs.modal', function() {
                options.onShown();
            });
            modalObj.on('hide.bs.modal', function() {
                options.onHide();
            });
            modalObj.on('hidden.bs.modal', function() {
                options.onHidden();
                modalObj.remove();
            });
            modalObj.modal(options.bootstrapModalOption);
        });    
    };
    
    $.extend({
        mdlg: function(options) {
            $("body").mdlg(options);
        },
    });
    
	$.mdlg.error = function(title,content){
		$("body").mdlg({
			title:title,
			content:'<div class="text-danger">'+content+'</div>'
		});
	}

	$.mdlg.alert = function(title,content){
		$("body").mdlg({
			title:title,
			content:content
		});
	}

	$.mdlg.confirm = function(title,content,onButtonClick){
		var ok = function (sender,modal,index){
			if(index == 0 && typeof onButtonClick == 'function'){
				onButtonClick();
			}
			$(this).closeDialog(modal)
		} 

		$("body").mdlg({
			title:title,
			buttons:["确定","取消"],
			buttonStyles:['btn-success','btn-default'],
			showCloseButton:false,
			content:content,
			onButtonClick:ok
		});
	}
})(jQuery);

/*
 * -----------------JQuery plugin-------------
 */
(function($,w) {
	$.fn.serializeJson = function() {
        var serializeObj = {};
        var temp = [];
        
        $(this.serializeArray()).each(function() {
            if (this.value.length > 0){
            	if(typeof serializeObj[this.name] == 'undefined'){
                    serializeObj[this.name] = this.value;
                    temp = [];
            	} else{
            		if(typeof serializeObj[this.name] == 'object'){
                		temp.concat(serializeObj[this.name]);
            		} else {
            			temp.push(serializeObj[this.name]);
            		}
            		temp.push(this.value);
            		
            		serializeObj[this.name] = temp;
            	}
            }
        });
        
        return serializeObj;
    };

    $.fn.formData = function(data) {
        var obj = data;
        var key, value, tagName, type, arr;

        $(this).resetForm();

        for (x in obj) {
            key = x;
            value = obj[x];

            $("[name='" + key + "'],[name='" + key + "[]']").each(function() {
                tagName = $(this)[0].tagName;
                type = $(this).attr('type');
                if (tagName == 'INPUT') {
                    if (type == 'radio') {
                        $(this).prop('checked', $(this).val() == value);
                    } else if (type == 'checkbox') {
                        arr = value.split(',');
                        for (var i = 0; i < arr.length; i++) {
                            if ($(this).val() == arr[i]) {
                                $(this).prop('checked', true);
                                break;
                            }
                        }
                    } else {
                        $(this).val(value);
                    }
                } else if (tagName == 'SELECT' || tagName == 'TEXTAREA') {
                    $(this).val(value);
                }
            });
        }
    }
    
    w.createDataSource = function(url,fields,group,aggregate) {
    	var pdata = new kendo.data.DataSource ({
    		transport: {
    			read: {
    				url: url,
    				dataType: 'json',
    				contentType: 'application/json; charset=utf-8',
    				type: "POST"
    			},
				parameterMap: function (options) {
					return JSON.stringify(options);
				}
    		},
    		pageSize: 20,
    		serverPaging:true,
    		serverSorting:true,
    		serverFiltering:true,
    		schema: {
    			data: function(d){return d.data},
    			total: function(d){return d.total},
    			errors: "errors",
    			model: {
    				fields: fields
    			}
    		},
    		group:group,
    		aggregate:aggregate,
			error: kendoErrors
		});
    	
    	var gdata = new kendo.data.DataSource ({
    		transport: {
    			read: {
    				url: url,
    				dataType: 'json',
    				contentType: 'application/json; charset=utf-8'
    			}
    		},
    		pageSize: 20,
    		serverPaging:true,
    		serverSorting:true,
    		serverFiltering:true,
    		schema: {
    			data: function(d){return d.data},
    			total: function(d){return d.total},
    			errors: "errors",
    			model: {
    				fields: fields
    			}
    		},
    		group:group,
    		aggregate:aggregate,
			error: kendoErrors
    	});

      return (typeof fields == "undefined") ? gdata : gdata;
    };
    
	$.fn.gridSelectedCols=function(colName){
		var gridObj = $(this).data("kendoGrid");
		var data = Array();
		gridObj.select().each(function() {
			var dataItem = gridObj.dataItem($(this));
			data.push(dataItem[colName]);
		});
		
		var res = {};
		res[colName] = data;

		return res;
	}

	$.fn.getTextField = function(value,list){
		var obj = this;

		if(typeof list != "undefined"){
			$.each(list,function(i,v){
				if(v.value == value){
					$(obj).html( v.text);
					return;
				}
			})
		}
		
	}
})(jQuery,window);
